import 'package:casdon/core/logger/log.dart';

import 'package:casdon/modules/recipe/data/model/recipe_category_model.dart';
import 'package:casdon/modules/recipe/domain/states/category_child_state.dart';
import 'package:casdon/modules/recipe/providers/recipe_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

/// 一次性加载分类数据的最简版 Provider
class CategoryChildNotifier
    extends FamilyAsyncNotifier<CategoryChildState, String> {
  @override
  Future<CategoryChildState> build(String moduleId) async {
    return await _fetchData(moduleId);
  }

  /// 仅执行一次请求
  Future<CategoryChildState> _fetchData(String moduleId) async {
    try {
      final tagRet = await ref
          .read(recipeCategoryUsecaseProvider)
          .execute(id: moduleId, pageNum: 1, pageSize: 100);

      // 解析分类
      if (tagRet.rows.isEmpty ||
          tagRet.rows.first.childrenList == null ||
          tagRet.rows.first.childrenList!.isEmpty) {
        return _buildFallbackState(moduleId);
      }

      final tags = RecipeCategoryModel.listFromApi(
        tagRet.rows.first.childrenList!,
      );

      final List<String> tabTitles = tags.map((e) => e.title).toList();
      // if (tags.isNotEmpty) {
      tabTitles.insert(0, '全部');
      tags.insert(0, _buildFallbackTag(moduleId));
      // }

      return CategoryChildState(
        tags: tags,
        titleTags: tabTitles,
        selectedIndex: 0,
      );
    } catch (e, st) {
      Log.e('CategoryChildNotifier失败', e, st);
      return _buildFallbackState(moduleId);
    }
  }

  void updateSelectedIndex(int index) {
    CategoryChildState? stateData = state.value;
    if (stateData == null) return;
    stateData = stateData.copyWith(selectedIndex: index);
    state = AsyncData(stateData);
  }

  RecipeCategoryModel _buildFallbackTag(String moduleId) {
    return RecipeCategoryModel(
      nodeType: 1,
      id: moduleId,
      sort: 0,
      childrenList: null,
      title: '全部',
      imgUrl: '',
    );
  }

  CategoryChildState _buildFallbackState(String moduleId) {
    return CategoryChildState(
      tags: [_buildFallbackTag(moduleId)],
      titleTags: const ['全部'],
      selectedIndex: 0,
    );
  }
}

/// Provider 定义
final categoryChildNotifierProvider =
    AsyncNotifierProviderFamily<
      CategoryChildNotifier,
      CategoryChildState,
      String
    >(CategoryChildNotifier.new);
